package cn.algorithm;

import java.awt.Point;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

public class Record {
    public final ArrayList<Point> moves = new ArrayList<>(); 
    public final ArrayList<Long> stepTimes = new ArrayList<>(); 
    public int boardSize = 11;
    public String firstPlayer = "Red";
    public String secondPlayer = "Blue";
    public String mode = "人机对战"; 
    public long startTime = System.currentTimeMillis();
    public long endTime = 0;

    public Record(int boardSize, String firstPlayer, String secondPlayer, String mode) {
        this.boardSize = boardSize;
        this.firstPlayer = firstPlayer;
        this.secondPlayer = secondPlayer;
        this.mode = mode;
    }

    public void addMove(int row, int col, long stepTimeMs) {
        moves.add(new Point(row, col));
        stepTimes.add(stepTimeMs);
    }

    public void addMove(Point p, long stepTimeMs) {
        addMove(p.x, p.y, stepTimeMs);
    }

    public void clear() {
        moves.clear();
        stepTimes.clear();
        startTime = System.currentTimeMillis();
        endTime = 0;
    }

    public static Path getSaveDirectoryInDocuments() {
        String userHome = System.getProperty("user.home");
        Path saveDir = Paths.get(userHome, "Documents", "hexgame");
        File directory = saveDir.toFile();
        if (!directory.exists()) {
            if (!directory.mkdirs()) {
                Path fallbackDir = Paths.get(System.getProperty("java.io.tmpdir"), "hexgame");
                if (!fallbackDir.toFile().exists()) fallbackDir.toFile().mkdirs();
                return fallbackDir;
            }
        }
        return saveDir;
    }

    /**
     * 导出棋谱到默认 Documents/hexgame 目录，文件名带时间戳
     * 导出格式兼容 HexReplayViewer 的解析规则（Moves 部分：R(A,1) / B(B,3) [123ms]）
     */
    public void writeToFile() {
        endTime = System.currentTimeMillis();
        Path saveDir = getSaveDirectoryInDocuments();
        File dir = saveDir.toFile();

        Date now = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH-mm", Locale.CHINA);
        String timeStamp = df.format(now);
        String fileName = "Hex-Record-" + timeStamp + ".txt";
        File outFile = new File(dir, fileName);

        try (PrintWriter out = new PrintWriter(outFile, "UTF-8")) {
            out.println("[棋类 \"Hex\"]");
            out.println("[时间 \"" + timeStamp + "\"]");
            out.println("[棋盘大小 \"" + boardSize + "\"]");
            out.println("[红方 \"" + firstPlayer + "\"]");
            out.println("[蓝方 \"" + secondPlayer + "\"]");
            out.println("[模式 \"" + mode + "\"]");
            out.println("[总步数 \"" + moves.size() + "\"]");
            out.println("[对局时长 \"" + getDurationString() + "\"]");
            out.println();

            out.println("Moves:");
            for (int i = 0; i < moves.size(); i++) {
                Point p = moves.get(i);
                int row = p.x; // 0-based
                int col = p.y; 
                String colLabel = colToLabel(col); 
                String rowLabel = String.valueOf(row + 1);
                String player = (i % 2 == 0) ? "R" : "B";
                //String stepTimeStr = (stepTimes.size() > i) ? (" [" + stepTimes.get(i) + "ms]") : "";
                out.print((i + 1) + ". " + player + "(" + colLabel + "," + rowLabel + ")" );
                if ((i + 1) % 5 == 0 || i == moves.size() - 1) out.println();
                else out.print("  ");
            }

            out.println();
            //out.println("棋谱已保存");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String colToLabel(int col) {
        if (col < 0) return "?";
        StringBuilder sb = new StringBuilder();
        int n = col;
        while (n >= 0) {
            int rem = n % 26;
            sb.insert(0, (char) ('A' + rem));
            n = n / 26 - 1;
        }
        return sb.toString();
    }

    private String getDurationString() {
        long duration = (endTime > startTime) ? (endTime - startTime) : 0;
        long seconds = duration / 1000;
        long minutes = seconds / 60;
        seconds = seconds % 60;
        return minutes + "分" + seconds + "秒";
    }
}
